package com.gaojinqi.sys.common.exception;

import com.gaojinqi.base.common.constant.RespConst;
import com.gaojinqi.base.common.vo.IResult;
import com.gaojinqi.base.common.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * sys工程异常拦截器
 *
 * @author gaojinqi
 * @version 1.0
 * @since 2020年06月12日
 */
@Slf4j
@RestControllerAdvice
public class SysExceptionHandler {

    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public IResult<?> authenticationException(HttpServletRequest request, AuthenticationException e) {
        long time = System.currentTimeMillis();
        log.warn("this is a shiro AuthenticationException at {},{}", time, e.getMessage());
        return ResultVo.fail(RespConst.RespEnum.UNAUTHORIZED.getCode(), e.getMessage());
    }

    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public IResult<?> authorizationException(HttpServletRequest request, AuthorizationException e) {
        long time = System.currentTimeMillis();
        log.warn("this is a shiro AuthorizationException at {},{}", time, e.getMessage());
        return ResultVo.fail(RespConst.RespEnum.NO_PERMISSIONS.getCode(), e.getMessage());
    }

}
